Merge "Normalize `input[type="search"]`"
[lhc/web/wiklou.git] / resources / src / mediawiki / mediawiki.Upload.BookletLayout.js
1 /*global moment*/
2 ( function ( $, mw, moment ) {
3
4 /**
5 * mw.Upload.BookletLayout encapsulates the process of uploading a file
6 * to MediaWiki using the {@link mw.Upload upload model}.
7 * The booklet emits events that can be used to get the stashed
8 * upload and the final file. It can be extended to accept
9 * additional fields from the user for specific scenarios like
10 * for Commons, or campaigns.
11 *
12 * ## Structure
13 *
14 * The {@link OO.ui.BookletLayout booklet layout} has three steps:
15 *
16 * - **Upload**: Has a {@link OO.ui.SelectFileWidget field} to get the file object.
17 *
18 * - **Information**: Has a {@link OO.ui.FormLayout form} to collect metadata. This can be
19 * extended.
20 *
21 * - **Insert**: Has details on how to use the file that was uploaded.
22 *
23 * Each step has a form associated with it defined in
24 * {@link #renderUploadForm renderUploadForm},
25 * {@link #renderInfoForm renderInfoForm}, and
26 * {@link #renderInsertForm renderInfoForm}. The
27 * {@link #getFile getFile},
28 * {@link #getFilename getFilename}, and
29 * {@link #getText getText} methods are used to get
30 * the information filled in these forms, required to call
31 * {@link mw.Upload mw.Upload}.
32 *
33 * ## Usage
34 *
35 * See the {@link mw.Upload.Dialog upload dialog}.
36 *
37 * The {@link #event-fileUploaded fileUploaded},
38 * and {@link #event-fileSaved fileSaved} events can
39 * be used to get details of the upload.
40 *
41 * ## Extending
42 *
43 * To extend using {@link mw.Upload mw.Upload}, override
44 * {@link #renderInfoForm renderInfoForm} to render
45 * the form required for the specific use-case. Update the
46 * {@link #getFilename getFilename}, and
47 * {@link #getText getText} methods to return data
48 * from your newly created form. If you added new fields you'll also have
49 * to update the {@link #clear} method.
50 *
51 * If you plan to use a different upload model, apart from what is mentioned
52 * above, you'll also have to override the
53 * {@link #createUpload createUpload} method to
54 * return the new model. The {@link #saveFile saveFile}, and
55 * the {@link #uploadFile uploadFile} methods need to be
56 * overridden to use the new model and data returned from the forms.
57 *
58 * @class
59 * @extends OO.ui.BookletLayout
60 *
61 * @constructor
62 * @param {Object} config Configuration options
63 * @cfg {jQuery} [$overlay] Overlay to use for widgets in the booklet
64 * @cfg {string} [filekey] Sets the stashed file to finish uploading. Overrides most of the file selection process, and fetches a thumbnail from the server.
65 */
66 mw.Upload.BookletLayout = function ( config ) {
67 // Parent constructor
68 mw.Upload.BookletLayout.parent.call( this, config );
69
70 this.$overlay = config.$overlay;
71
72 this.filekey = config.filekey;
73
74 this.renderUploadForm();
75 this.renderInfoForm();
76 this.renderInsertForm();
77
78 this.addPages( [
79 new OO.ui.PageLayout( 'upload', {
80 scrollable: true,
81 padded: true,
82 content: [ this.uploadForm ]
83 } ),
84 new OO.ui.PageLayout( 'info', {
85 scrollable: true,
86 padded: true,
87 content: [ this.infoForm ]
88 } ),
89 new OO.ui.PageLayout( 'insert', {
90 scrollable: true,
91 padded: true,
92 content: [ this.insertForm ]
93 } )
94 ] );
95 };
96
97 /* Setup */
98
99 OO.inheritClass( mw.Upload.BookletLayout, OO.ui.BookletLayout );
100
101 /* Events */
102
103 /**
104 * Progress events for the uploaded file
105 *
106 * @event fileUploadProgress
107 * @param {number} progress In percentage
108 * @param {Object} duration Duration object from `moment.duration()`
109 */
110
111 /**
112 * The file has finished uploading
113 *
114 * @event fileUploaded
115 */
116
117 /**
118 * The file has been saved to the database
119 *
120 * @event fileSaved
121 * @param {Object} imageInfo See mw.Upload#getImageInfo
122 */
123
124 /**
125 * The upload form has changed
126 *
127 * @event uploadValid
128 * @param {boolean} isValid The form is valid
129 */
130
131 /**
132 * The info form has changed
133 *
134 * @event infoValid
135 * @param {boolean} isValid The form is valid
136 */
137
138 /* Properties */
139
140 /**
141 * @property {OO.ui.FormLayout} uploadForm
142 * The form rendered in the first step to get the file object.
143 * Rendered in {@link #renderUploadForm renderUploadForm}.
144 */
145
146 /**
147 * @property {OO.ui.FormLayout} infoForm
148 * The form rendered in the second step to get metadata.
149 * Rendered in {@link #renderInfoForm renderInfoForm}
150 */
151
152 /**
153 * @property {OO.ui.FormLayout} insertForm
154 * The form rendered in the third step to show usage
155 * Rendered in {@link #renderInsertForm renderInsertForm}
156 */
157
158 /* Methods */
159
160 /**
161 * Initialize for a new upload
162 *
163 * @return {jQuery.Promise} Promise resolved when everything is initialized
164 */
165 mw.Upload.BookletLayout.prototype.initialize = function () {
166 var booklet = this;
167
168 this.clear();
169 this.upload = this.createUpload();
170
171 this.setPage( 'upload' );
172
173 if ( this.filekey ) {
174 this.setFilekey( this.filekey );
175 }
176
177 return this.upload.getApi().then(
178 function ( api ) {
179 // If the user can't upload anything, don't give them the option to.
180 return api.getUserInfo().then(
181 function ( userInfo ) {
182 if ( userInfo.rights.indexOf( 'upload' ) === -1 ) {
183 // TODO Use a better error message when not all logged-in users can upload
184 booklet.getPage( 'upload' ).$element.msg( 'api-error-mustbeloggedin' );
185 }
186 return $.Deferred().resolve();
187 },
188 function () {
189 return $.Deferred().resolve();
190 }
191 );
192 },
193 function ( errorMsg ) {
194 booklet.getPage( 'upload' ).$element.msg( errorMsg );
195 return $.Deferred().resolve();
196 }
197 );
198 };
199
200 /**
201 * Create a new upload model
202 *
203 * @protected
204 * @return {mw.Upload} Upload model
205 */
206 mw.Upload.BookletLayout.prototype.createUpload = function () {
207 return new mw.Upload();
208 };
209
210 /* Uploading */
211
212 /**
213 * Uploads the file that was added in the upload form. Uses
214 * {@link #getFile getFile} to get the HTML5
215 * file object.
216 *
217 * @protected
218 * @fires fileUploadProgress
219 * @fires fileUploaded
220 * @return {jQuery.Promise}
221 */
222 mw.Upload.BookletLayout.prototype.uploadFile = function () {
223 var deferred = $.Deferred(),
224 startTime = new Date(),
225 layout = this,
226 file = this.getFile();
227
228 this.setPage( 'info' );
229
230 if ( this.filekey ) {
231 if ( file === null ) {
232 // Someone gonna get-a hurt real bad
233 throw new Error( 'filekey not passed into file select widget, which is impossible. Quitting while we\'re behind.' );
234 }
235
236 // Stashed file already uploaded.
237 deferred.resolve();
238 this.uploadPromise = deferred;
239 this.emit( 'fileUploaded' );
240 return deferred;
241 }
242
243 this.setFilename( file.name );
244
245 this.upload.setFile( file );
246 // The original file name might contain invalid characters, so use our sanitized one
247 this.upload.setFilename( this.getFilename() );
248
249 this.uploadPromise = this.upload.uploadToStash();
250 this.uploadPromise.then( function () {
251 deferred.resolve();
252 layout.emit( 'fileUploaded' );
253 }, function () {
254 // These errors will be thrown while the user is on the info page.
255 // Pretty sure it's impossible to get a warning other than 'stashfailed' here, which should
256 // really be an error...
257 var errorMessage = layout.getErrorMessageForStateDetails();
258 deferred.reject( errorMessage );
259 }, function ( progress ) {
260 var elapsedTime = new Date() - startTime,
261 estimatedTotalTime = ( 1 / progress ) * elapsedTime,
262 estimatedRemainingTime = moment.duration( estimatedTotalTime - elapsedTime );
263 layout.emit( 'fileUploadProgress', progress, estimatedRemainingTime );
264 } );
265
266 // If there is an error in uploading, come back to the upload page
267 deferred.fail( function () {
268 layout.setPage( 'upload' );
269 } );
270
271 return deferred;
272 };
273
274 /**
275 * Saves the stash finalizes upload. Uses
276 * {@link #getFilename getFilename}, and
277 * {@link #getText getText} to get details from
278 * the form.
279 *
280 * @protected
281 * @fires fileSaved
282 * @return {jQuery.Promise} Rejects the promise with an
283 * {@link OO.ui.Error error}, or resolves if the upload was successful.
284 */
285 mw.Upload.BookletLayout.prototype.saveFile = function () {
286 var layout = this,
287 deferred = $.Deferred();
288
289 this.upload.setFilename( this.getFilename() );
290 this.upload.setText( this.getText() );
291
292 this.uploadPromise.then( function () {
293 layout.upload.finishStashUpload().then( function () {
294 var name;
295
296 // Normalize page name and localise the 'File:' prefix
297 name = new mw.Title( 'File:' + layout.upload.getFilename() ).toString();
298 layout.filenameUsageWidget.setValue( '[[' + name + ']]' );
299 layout.setPage( 'insert' );
300
301 deferred.resolve();
302 layout.emit( 'fileSaved', layout.upload.getImageInfo() );
303 }, function () {
304 var errorMessage = layout.getErrorMessageForStateDetails();
305 deferred.reject( errorMessage );
306 } );
307 } );
308
309 return deferred.promise();
310 };
311
312 /**
313 * Get an error message (as OO.ui.Error object) that should be displayed to the user for current
314 * state and state details.
315 *
316 * @protected
317 * @return {OO.ui.Error} Error to display for given state and details.
318 */
319 mw.Upload.BookletLayout.prototype.getErrorMessageForStateDetails = function () {
320 var message,
321 state = this.upload.getState(),
322 stateDetails = this.upload.getStateDetails(),
323 error = stateDetails.error,
324 warnings = stateDetails.upload && stateDetails.upload.warnings;
325
326 if ( state === mw.Upload.State.ERROR ) {
327 if ( !error ) {
328 // If there's an 'exception' key, this might be a timeout, or other connection problem
329 return new OO.ui.Error(
330 $( '<p>' ).msg( 'api-error-unknownerror', JSON.stringify( stateDetails ) ),
331 { recoverable: false }
332 );
333 }
334
335 // HACK We should either have a hook here to allow TitleBlacklist to handle this, or just have
336 // TitleBlacklist produce sane error messages that can be displayed without arcane knowledge
337 if ( error.info === 'TitleBlacklist prevents this title from being created' ) {
338 // HACK Apparently the only reliable way to determine whether TitleBlacklist was involved
339 return new OO.ui.Error(
340 // HACK TitleBlacklist doesn't have a sensible message, this one is from UploadWizard
341 $( '<p>' ).msg( 'api-error-blacklisted' ),
342 { recoverable: false }
343 );
344 }
345
346 if ( error.code === 'protectedpage' ) {
347 message = mw.message( 'protectedpagetext' );
348 } else {
349 message = mw.message( 'api-error-' + error.code );
350 if ( !message.exists() ) {
351 message = mw.message( 'api-error-unknownerror', JSON.stringify( stateDetails ) );
352 }
353 }
354 return new OO.ui.Error(
355 $( '<p>' ).append( message.parseDom() ),
356 { recoverable: false }
357 );
358 }
359
360 if ( state === mw.Upload.State.WARNING ) {
361 // We could get more than one of these errors, these are in order
362 // of importance. For example fixing the thumbnail like file name
363 // won't help the fact that the file already exists.
364 if ( warnings.stashfailed !== undefined ) {
365 return new OO.ui.Error(
366 $( '<p>' ).msg( 'api-error-stashfailed' ),
367 { recoverable: false }
368 );
369 } else if ( warnings.exists !== undefined ) {
370 return new OO.ui.Error(
371 $( '<p>' ).msg( 'fileexists', 'File:' + warnings.exists ),
372 { recoverable: false }
373 );
374 } else if ( warnings[ 'exists-normalized' ] !== undefined ) {
375 return new OO.ui.Error(
376 $( '<p>' ).msg( 'fileexists', 'File:' + warnings[ 'exists-normalized' ] ),
377 { recoverable: false }
378 );
379 } else if ( warnings[ 'page-exists' ] !== undefined ) {
380 return new OO.ui.Error(
381 $( '<p>' ).msg( 'filepageexists', 'File:' + warnings[ 'page-exists' ] ),
382 { recoverable: false }
383 );
384 } else if ( warnings.duplicate !== undefined ) {
385 return new OO.ui.Error(
386 $( '<p>' ).msg( 'api-error-duplicate', warnings.duplicate.length ),
387 { recoverable: false }
388 );
389 } else if ( warnings[ 'thumb-name' ] !== undefined ) {
390 return new OO.ui.Error(
391 $( '<p>' ).msg( 'filename-thumb-name' ),
392 { recoverable: false }
393 );
394 } else if ( warnings[ 'bad-prefix' ] !== undefined ) {
395 return new OO.ui.Error(
396 $( '<p>' ).msg( 'filename-bad-prefix', warnings[ 'bad-prefix' ] ),
397 { recoverable: false }
398 );
399 } else if ( warnings[ 'duplicate-archive' ] !== undefined ) {
400 return new OO.ui.Error(
401 $( '<p>' ).msg( 'api-error-duplicate-archive', 1 ),
402 { recoverable: false }
403 );
404 } else if ( warnings[ 'was-deleted' ] !== undefined ) {
405 return new OO.ui.Error(
406 $( '<p>' ).msg( 'api-error-was-deleted' ),
407 { recoverable: false }
408 );
409 } else if ( warnings.badfilename !== undefined ) {
410 // Change the name if the current name isn't acceptable
411 // TODO This might not really be the best place to do this
412 this.setFilename( warnings.badfilename );
413 return new OO.ui.Error(
414 $( '<p>' ).msg( 'badfilename', warnings.badfilename )
415 );
416 } else {
417 return new OO.ui.Error(
418 // Let's get all the help we can if we can't pin point the error
419 $( '<p>' ).msg( 'api-error-unknown-warning', JSON.stringify( stateDetails ) ),
420 { recoverable: false }
421 );
422 }
423 }
424 };
425
426 /* Form renderers */
427
428 /**
429 * Renders and returns the upload form and sets the
430 * {@link #uploadForm uploadForm} property.
431 *
432 * @protected
433 * @fires selectFile
434 * @return {OO.ui.FormLayout}
435 */
436 mw.Upload.BookletLayout.prototype.renderUploadForm = function () {
437 var fieldset,
438 layout = this;
439
440 this.selectFileWidget = this.getFileWidget();
441 fieldset = new OO.ui.FieldsetLayout();
442 fieldset.addItems( [ this.selectFileWidget ] );
443 this.uploadForm = new OO.ui.FormLayout( { items: [ fieldset ] } );
444
445 // Validation (if the SFW is for a stashed file, this never fires)
446 this.selectFileWidget.on( 'change', this.onUploadFormChange.bind( this ) );
447
448 this.selectFileWidget.on( 'change', function () {
449 layout.updateFilePreview();
450 } );
451
452 return this.uploadForm;
453 };
454
455 /**
456 * Gets the widget for displaying or inputting the file to upload.
457 *
458 * @return {OO.ui.SelectFileWidget|mw.widgets.StashedFileWidget}
459 */
460 mw.Upload.BookletLayout.prototype.getFileWidget = function () {
461 if ( this.filekey ) {
462 return new mw.widgets.StashedFileWidget( {
463 filekey: this.filekey
464 } );
465 }
466
467 return new OO.ui.SelectFileWidget( {
468 showDropTarget: true
469 } );
470 };
471
472 /**
473 * Updates the file preview on the info form when a file is added.
474 *
475 * @protected
476 */
477 mw.Upload.BookletLayout.prototype.updateFilePreview = function () {
478 this.selectFileWidget.loadAndGetImageUrl().done( function ( url ) {
479 this.filePreview.$element.find( 'p' ).remove();
480 this.filePreview.$element.css( 'background-image', 'url(' + url + ')' );
481 this.infoForm.$element.addClass( 'mw-upload-bookletLayout-hasThumbnail' );
482 }.bind( this ) ).fail( function () {
483 this.filePreview.$element.find( 'p' ).remove();
484 if ( this.selectFileWidget.getValue() ) {
485 this.filePreview.$element.append(
486 $( '<p>' ).text( this.selectFileWidget.getValue().name )
487 );
488 }
489 this.filePreview.$element.css( 'background-image', '' );
490 this.infoForm.$element.removeClass( 'mw-upload-bookletLayout-hasThumbnail' );
491 }.bind( this ) );
492 };
493
494 /**
495 * Handle change events to the upload form
496 *
497 * @protected
498 * @fires uploadValid
499 */
500 mw.Upload.BookletLayout.prototype.onUploadFormChange = function () {
501 this.emit( 'uploadValid', !!this.selectFileWidget.getValue() );
502 };
503
504 /**
505 * Renders and returns the information form for collecting
506 * metadata and sets the {@link #infoForm infoForm}
507 * property.
508 *
509 * @protected
510 * @return {OO.ui.FormLayout}
511 */
512 mw.Upload.BookletLayout.prototype.renderInfoForm = function () {
513 var fieldset;
514
515 this.filePreview = new OO.ui.Widget( {
516 classes: [ 'mw-upload-bookletLayout-filePreview' ]
517 } );
518 this.progressBarWidget = new OO.ui.ProgressBarWidget( {
519 progress: 0
520 } );
521 this.filePreview.$element.append( this.progressBarWidget.$element );
522
523 this.filenameWidget = new OO.ui.TextInputWidget( {
524 indicator: 'required',
525 required: true,
526 validate: /.+/
527 } );
528 this.descriptionWidget = new OO.ui.TextInputWidget( {
529 indicator: 'required',
530 required: true,
531 validate: /\S+/,
532 multiline: true,
533 autosize: true
534 } );
535
536 fieldset = new OO.ui.FieldsetLayout( {
537 label: mw.msg( 'upload-form-label-infoform-title' )
538 } );
539 fieldset.addItems( [
540 new OO.ui.FieldLayout( this.filenameWidget, {
541 label: mw.msg( 'upload-form-label-infoform-name' ),
542 align: 'top',
543 help: mw.msg( 'upload-form-label-infoform-name-tooltip' )
544 } ),
545 new OO.ui.FieldLayout( this.descriptionWidget, {
546 label: mw.msg( 'upload-form-label-infoform-description' ),
547 align: 'top',
548 help: mw.msg( 'upload-form-label-infoform-description-tooltip' )
549 } )
550 ] );
551 this.infoForm = new OO.ui.FormLayout( {
552 classes: [ 'mw-upload-bookletLayout-infoForm' ],
553 items: [ this.filePreview, fieldset ]
554 } );
555
556 this.on( 'fileUploadProgress', function ( progress ) {
557 this.progressBarWidget.setProgress( progress * 100 );
558 }.bind( this ) );
559
560 this.filenameWidget.on( 'change', this.onInfoFormChange.bind( this ) );
561 this.descriptionWidget.on( 'change', this.onInfoFormChange.bind( this ) );
562
563 return this.infoForm;
564 };
565
566 /**
567 * Handle change events to the info form
568 *
569 * @protected
570 * @fires infoValid
571 */
572 mw.Upload.BookletLayout.prototype.onInfoFormChange = function () {
573 var layout = this;
574 $.when(
575 this.filenameWidget.getValidity(),
576 this.descriptionWidget.getValidity()
577 ).done( function () {
578 layout.emit( 'infoValid', true );
579 } ).fail( function () {
580 layout.emit( 'infoValid', false );
581 } );
582 };
583
584 /**
585 * Renders and returns the insert form to show file usage and
586 * sets the {@link #insertForm insertForm} property.
587 *
588 * @protected
589 * @return {OO.ui.FormLayout}
590 */
591 mw.Upload.BookletLayout.prototype.renderInsertForm = function () {
592 var fieldset;
593
594 this.filenameUsageWidget = new OO.ui.TextInputWidget();
595 fieldset = new OO.ui.FieldsetLayout( {
596 label: mw.msg( 'upload-form-label-usage-title' )
597 } );
598 fieldset.addItems( [
599 new OO.ui.FieldLayout( this.filenameUsageWidget, {
600 label: mw.msg( 'upload-form-label-usage-filename' ),
601 align: 'top'
602 } )
603 ] );
604 this.insertForm = new OO.ui.FormLayout( { items: [ fieldset ] } );
605
606 return this.insertForm;
607 };
608
609 /* Getters */
610
611 /**
612 * Gets the file object from the
613 * {@link #uploadForm upload form}.
614 *
615 * @protected
616 * @return {File|null}
617 */
618 mw.Upload.BookletLayout.prototype.getFile = function () {
619 return this.selectFileWidget.getValue();
620 };
621
622 /**
623 * Gets the file name from the
624 * {@link #infoForm information form}.
625 *
626 * @protected
627 * @return {string}
628 */
629 mw.Upload.BookletLayout.prototype.getFilename = function () {
630 var filename = this.filenameWidget.getValue();
631 if ( this.filenameExtension ) {
632 filename += '.' + this.filenameExtension;
633 }
634 return filename;
635 };
636
637 /**
638 * Prefills the {@link #infoForm information form} with the given filename.
639 *
640 * @protected
641 * @param {string} filename
642 */
643 mw.Upload.BookletLayout.prototype.setFilename = function ( filename ) {
644 var title = mw.Title.newFromFileName( filename );
645
646 if ( title ) {
647 this.filenameWidget.setValue( title.getNameText() );
648 this.filenameExtension = mw.Title.normalizeExtension( title.getExtension() );
649 } else {
650 // Seems to happen for files with no extension, which should fail some checks anyway...
651 this.filenameWidget.setValue( filename );
652 this.filenameExtension = null;
653 }
654 };
655
656 /**
657 * Gets the page text from the
658 * {@link #infoForm information form}.
659 *
660 * @protected
661 * @return {string}
662 */
663 mw.Upload.BookletLayout.prototype.getText = function () {
664 return this.descriptionWidget.getValue();
665 };
666
667 /* Setters */
668
669 /**
670 * Sets the file object
671 *
672 * @protected
673 * @param {File|null} file File to select
674 */
675 mw.Upload.BookletLayout.prototype.setFile = function ( file ) {
676 this.selectFileWidget.setValue( file );
677 };
678
679 /**
680 * Sets the filekey of a file already stashed on the server
681 * as the target of this upload operation.
682 *
683 * @protected
684 * @param {string} filekey
685 */
686 mw.Upload.BookletLayout.prototype.setFilekey = function ( filekey ) {
687 this.upload.setFilekey( this.filekey );
688 this.selectFileWidget.setValue( filekey );
689
690 this.onUploadFormChange();
691 };
692
693 /**
694 * Clear the values of all fields
695 *
696 * @protected
697 */
698 mw.Upload.BookletLayout.prototype.clear = function () {
699 this.selectFileWidget.setValue( null );
700 this.progressBarWidget.setProgress( 0 );
701 this.filenameWidget.setValue( null ).setValidityFlag( true );
702 this.descriptionWidget.setValue( null ).setValidityFlag( true );
703 this.filenameUsageWidget.setValue( null );
704 };
705
706 }( jQuery, mediaWiki, moment ) );